package kr.co.kiso.usr.common;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.co.kiso.usr.am.gr.service.AMGRService;
import kr.co.kiso.usr.am.gr.vo.AMGRVo;
import kr.co.kiso.usr.exception.RequiredLoginException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;

public abstract class BaseController {
	protected Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private AMGRService loginAmgrService;
	
	protected boolean isLogin(HttpServletRequest request) throws Exception {
				
		Map usr = (Map) request.getSession().getAttribute("userInfo");
		if( null == usr || "".equals(usr.get("ADMIN_ID"))){
			return false;
		}else{
			AMGRVo vo = new AMGRVo();
			vo.setAdmin_id((String)usr.get("ADMIN_ID"));

			Map map =loginAmgrService.amgr181Q(vo);
		
			//메뉴랑 권한 가져오기는 쿼리
//				국문으로 셋팅
			int menu_top_seq =Integer.parseInt(  String.valueOf( request.getSession().getAttribute("menuTopSeq"))); 
			vo.setMenu_seq_no(menu_top_seq );
			
			List list = loginAmgrService.amgr190Q(vo);
			
			request.getSession().setAttribute("menuList", list);
			request.getSession().setAttribute("userInfo", map);
		
			return true;
		}
	}
	
	protected void isMember(HttpServletRequest req,
			HttpServletResponse res) throws Exception{
		Map user = (Map) req.getSession().getAttribute("userInfo");
		/* 로그인 여부 검사*/
		if (!isLogin(req) ) {
//			String url = URLEncoder.encode(req.getRequestURI().replace(req.getContextPath(), ""),"UTF-8");
			String param = requestPram2Str(req);
			String url = req.getRequestURI().replace(req.getContextPath(), "");
			throw new RequiredLoginException(url+ param);
		}
	}

	public String requestPram2Str(HttpServletRequest httprequest) {

		Enumeration enum1 = httprequest.getParameterNames();

		int count = httprequest.getParameterMap().size();
		if(0==count)return "";

		StringBuffer ret=new StringBuffer("?");;

		for (int i = 0; i < count; i++) {
			if(i!=0){
				ret.append("&");
			}
			String cd = (String)enum1.nextElement();
			
			ret.append(cd);
			ret.append("=");
			ret.append(httprequest.getParameter(cd));
			
		}

		return ret.toString();
	}
	
	public Map requestPram2Map(HttpServletRequest httprequest) {

		Enumeration enum1 = httprequest.getParameterNames();

		int count = httprequest.getParameterMap().size();
		Map rtMap = new HashMap();
		if(0==count)return rtMap;
		
		for (int i = 0; i < count; i++) {
			
			String cd = (String)enum1.nextElement();
			rtMap.put(cd, httprequest.getParameter(cd));
		}

		return rtMap;
	}

}
